package com.future.mayi.activity;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.future.baselib.entity.DefaultResponse;
import com.future.baselib.utils.ApiCst;
import com.future.baselib.utils.CommonUtils;
import com.future.baselib.utils.HttpRequest;
import com.future.mayi.R;
import com.future.mayi.app.App;
import com.future.mayi.dialog.CommonDialog;
import com.future.mayi.dialog.ConfirmGoodsDialog;
import com.future.mayi.dialog.KefuDialog;
import com.future.mayi.model.GoodsItemModel;
import com.future.mayi.model.GoodsOrderModel;
import com.future.mayi.model.KefuModel;
import com.future.mayi.model.interfaces.DialogEnterListener;
import com.future.mayi.response.GoodsOrderInfoResponse;
import com.future.mayi.response.KefuResponse;
import com.future.mayi.utils.HCUtils;
import com.future.mayi.utils.HtmlFormat;
import com.future.mayi.utils.KefuUtils;
import com.future.mayi.utils.PriceUtils;

import org.json.JSONException;
import org.json.JSONObject;

import butterknife.BindView;
import butterknife.OnClick;

public class GoodsOrderActivity extends BaseTitleActivity {
    @BindView(R.id.tv_express_company)
    TextView tvExpressCompany;
    @BindView(R.id.tv_express_find)
    TextView tvExpressFind;
    @BindView(R.id.tv_express_code)
    TextView tvExpressCode;
    @BindView(R.id.ll_express)
    LinearLayout llExpress;
    @BindView(R.id.ll_no_express)
    LinearLayout llNoExpress;
    @BindView(R.id.title_view_line)
    View titleViewLine;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.tv_phone)
    TextView tvPhone;
    @BindView(R.id.tv_address)
    TextView tvAddress;
    @BindView(R.id.ll_address)
    LinearLayout llAddress;
    @BindView(R.id.ll_goods)
    LinearLayout llGoods;
    @BindView(R.id.tv_all_price)
    TextView tvAllPrice;
    @BindView(R.id.tv_freight_price)
    TextView tvFreightPrice;
    @BindView(R.id.tv_price)
    TextView tvPrice;
    @BindView(R.id.ll_server)
    LinearLayout llServer;
    @BindView(R.id.tv_order_code)
    TextView tvOrderCode;
    @BindView(R.id.tv_order_time)
    TextView tvOrderTime;
    @BindView(R.id.tv_order_state)
    TextView tvOrderState;
    @BindView(R.id.tv_enter)
    TextView tvEnter;
    @BindView(R.id.ll_enter)
    View llEnter;
    @BindView(R.id.tv_commission)
    TextView tvCommission;
    @BindView(R.id.tv_remark)
    TextView tvRemark;
    @BindView(R.id.ll_remark)
    View llRemark;

    private String orderId;
    private GoodsOrderModel model;
    private LayoutInflater mInflater;
    private boolean backMain = false;
    private boolean isVisitor = false;


    public static void startActivity(Context context, String orderId) {
        context.startActivity(new Intent(context, GoodsOrderActivity.class).putExtra("orderId", orderId));
    }

    public static void startActivity(Context context, boolean isVisitor, String orderId) {
        context.startActivity(new Intent(context, GoodsOrderActivity.class).putExtra("orderId", orderId).putExtra("isVisitor", isVisitor));
    }

    public static void startActivity(Context context, String orderId, boolean backMain) {
        context.startActivity(new Intent(context, GoodsOrderActivity.class).putExtra("orderId", orderId).putExtra("backMain", backMain));
    }

    public static void startActivity(Context context, GoodsOrderModel model) {
        context.startActivity(new Intent(context, GoodsOrderActivity.class).putExtra("model", model));
    }


    @Override
    protected void initTopBar() {
        initBack();
        getTitleText().setText("待付款");
    }

    @Override
    protected void initLayout() {
        setContentView(R.layout.activity_goods_order);
    }

    @Override
    protected void initView() {
        mInflater = LayoutInflater.from(this);
    }

    @Override
    protected void initDates() {
        orderId = getIntent().getStringExtra("orderId");
        backMain = getIntent().getBooleanExtra("backMain", false);
        isVisitor = getIntent().getBooleanExtra("isVisitor", false);
        if (getIntent().getSerializableExtra("model") != null)
            model = (GoodsOrderModel) getIntent().getSerializableExtra("model");
        if (model != null) {
            orderId = String.valueOf(model.getOrder_id());
        }
        setView();
    }

    private void setView() {
        if (model == null) return;
        if (is_refund == -1) return;
        TextView tvTitle = getTitleText();
        TextView tvRight = getRightText();
        tvRight.setVisibility(View.GONE);
        llExpress.setVisibility(View.GONE);
        llNoExpress.setVisibility(View.GONE);
        titleViewLine.setVisibility(View.GONE);
        llAddress.setVisibility(View.GONE);
        String payType = "";
        switch (model.getPay_type()) {
            case 1:
                payType = "支付宝";
                break;
            case 2:
                payType = "微信";
                break;
            case 3:
                payType = "余额";
                break;
        }
        payType = "（" + payType + "支付）";

        //订单状态:订单状态:0=待支付,10=已支付,20=已发货,30=已确认,待评价,50=已完成,60=已取消,70=退款中,71=退款失败,80=退款成功
        switch (model.getStatus()) {
            // 0-待付款
            case 0:
                llEnter.setVisibility(View.VISIBLE);
                setText(tvEnter, "立即支付");
                setText(tvTitle, "待付款");
                setText(tvOrderState, "待付款");
                tvRight.setVisibility(View.VISIBLE);
                setText(tvRight, "取消订单");
                break;
            // 10-已支付 待发货
            case 10:
                llEnter.setVisibility(View.GONE);
                setText(tvTitle, "待发货");
                setText(tvOrderState, "待发货" + payType);
                if (model.getChange_address_status() == 1) {
                    tvRight.setVisibility(View.VISIBLE);
                    setText(tvRight, "修改地址");
                }
                break;
            // 20- 已发货 待收货
            case 20:
                llEnter.setVisibility(View.VISIBLE);
                setText(tvEnter, "确认收货");
                setLlExpress();
                setText(tvTitle, "待收货");
                setText(tvOrderState, "待收货" + payType);
                tvRight.setVisibility(View.VISIBLE);
                setText(tvRight, "复制物流信息");
                break;
            // 30-已确认
            case 30:
                // 50-已完成
            case 50:
                llEnter.setVisibility(View.GONE);
                setText(tvTitle, "已完成");
                setText(tvOrderState, "已完成" + payType);
                tvRight.setVisibility(View.VISIBLE);
                setText(tvRight, "复制物流信息");
                break;
            // 90-已取消
            case 60:
                llEnter.setVisibility(View.GONE);
                setText(tvTitle, "已取消");
                setText(tvOrderState, "已取消");
                break;
            // 70-退款中
            case 70:
                llEnter.setVisibility(View.GONE);
                setText(tvTitle, "退款审核中");
                setText(tvOrderState, "退款审核中" + payType);
                titleViewLine.setVisibility(View.VISIBLE);
                break;
            //71=退款失败,
            case 71:
                llEnter.setVisibility(View.GONE);
                setText(tvTitle, "退款失败");
                setText(tvOrderState, "退款失败" + payType);
                titleViewLine.setVisibility(View.VISIBLE);
                break;
            // 80=退款成功
            case 80:
                llEnter.setVisibility(View.GONE);
                setText(tvTitle, "退款成功");
                setText(tvOrderState, "退款成功" + payType);
                titleViewLine.setVisibility(View.VISIBLE);
                break;

        }

        llAddress.setVisibility(View.VISIBLE);
        setText(tvName, model.getAddress_user());
        setText(tvPhone, model.getAddress_tel());
        setText(tvAddress, model.getAddress());


        String rebate_status = "(" + (model.getRebate_status() == 1 ? "已到账" : (model.getRebate_status() == 10 ? "已退回" : "待到账")) + ")";
        if (model.getStatus() == 0 || model.getStatus() == 60) {
            rebate_status = "";
        }
        if (isVisitor) {
            setText(tvCommission, "¥ " + PriceUtils.getPriceText2(model.getSub_rebate()) + rebate_status);
        } else {
            setText(tvCommission, "¥ " + PriceUtils.getPriceText2(model.getRebate()) + rebate_status);
        }

        llGoods.removeAllViews();
        if (model.getGoods_item() != null && model.getGoods_item().size() > 0) {
            View viewLine = null;
            for (GoodsItemModel model : model.getGoods_item()) {
                View view = mInflater.inflate(R.layout.layout_goods_order_goods_item, llGoods, false);
                llGoods.addView(view);
                ImageView ivImg = view.findViewById(R.id.iv_img);
                TextView tvGoodsTitle = view.findViewById(R.id.tv_title);
                TextView tvGoodsPrice = view.findViewById(R.id.tv_goods_price);
                TextView tvValue = view.findViewById(R.id.tv_value);
                TextView tvRefundStatus = view.findViewById(R.id.tv_refund);
                viewLine = view.findViewById(R.id.view_line);
                HCUtils.loadWebImg(this, ivImg, model.getMain_img());
                tvGoodsTitle.setText(model.getGoods_name());
                tvValue.setText(model.getGoods_attr() + ",x" + (model.getBuy_num()));
                tvGoodsPrice.setText(PriceUtils.getPriceText2(model.getUnit_price()));
                if (isVisitor) continue;
                //0=待支付,10=已支付,20=已发货,30=已确认,待评价,50=已完成,60=已取消,70=退款中,71=退款失败,80=退款成功
                if (this.model.getStatus() != 0) {
                    String status = null;
                    int drawable = 0;
                    int color = 0;
                    switch (model.getOrder_goods_status()) {
                        case 0:
                            if ((this.model.getStatus() == 10 || this.model.getStatus() == 20) && is_refund == 1) {
                                status = "申请退款";
                                drawable = R.drawable.bg_goods_order_refund_0;
                                color = R.color.bg_C6C6C6;
                            }
                            break;
                        case 1:
                        case 2:
                            status = "退款中";
                            drawable = R.drawable.bg_goods_order_refund_1;
                            color = R.color.red;
                            break;
                        case 10:
                        case 11:
                            status = "退款成功";
                            drawable = R.drawable.bg_goods_order_refund_4;
                            color = R.color.bg_FFAE00;
                            break;
                        case 30:
                            status = "退款被拒绝";
                            drawable = R.drawable.bg_goods_order_refund_0;
                            color = R.color.bg_C6C6C6;
                            break;
                    }

                    if (status != null) {
                        tvRefundStatus.setTextColor(getResources().getColor(color));
                        tvRefundStatus.setBackgroundResource(drawable);
                        tvRefundStatus.setText(status);
                        tvRefundStatus.setTag(model);
                        tvRefundStatus.setOnClickListener(this);
                        tvRefundStatus.setVisibility(View.VISIBLE);
                    }
                }
                view.setTag(model);
                view.setOnClickListener(this);
            }
            if (viewLine != null) viewLine.setVisibility(View.GONE);
        }

        setText(tvAllPrice, "¥ ".concat(PriceUtils.getPriceText2(model.getAll_total_price())));
        setText(tvFreightPrice, "+¥ ".concat(PriceUtils.getPriceText2(model.getPost_free())));
        setText(tvPrice, "¥ ".concat(PriceUtils.getPriceText2(model.getPay_price())));
        setText(tvOrderCode, "订单编号：".concat(model.getOrder_no() == null ? "" : model.getOrder_no()));
        setText(tvOrderTime, model.getCreatetime());


        setText(tvRemark, TextUtils.isEmpty(model.getMemo()) ? "无" : model.getMemo());


        if (isVisitor) {
            //llRemark.setVisibility(View.GONE);
            llEnter.setVisibility(View.GONE);
            tvRight.setVisibility(View.GONE);
            llExpress.setVisibility(View.GONE);
            llNoExpress.setVisibility(View.GONE);
            titleViewLine.setVisibility(View.GONE);
            llAddress.setVisibility(View.GONE);
        }
    }

    /**
     * 设置物流
     */
    public void setLlExpress() {
        titleViewLine.setVisibility(View.VISIBLE);
        if (model.getExpress_type() == 0 && (!TextUtils.isEmpty(model.getExpress_no()))) {
            llNoExpress.setVisibility(View.GONE);
            llExpress.setVisibility(View.VISIBLE);
            setText(tvExpressCompany, model.getExpress_name());
            setText(tvExpressCode, "物流单号：" + model.getExpress_no());
        } else if (model.getExpress_type() == 10) {
            llNoExpress.setVisibility(View.VISIBLE);
            llExpress.setVisibility(View.GONE);
        } else {
            titleViewLine.setVisibility(View.GONE);
        }
    }


    //退款入口是否关闭
    private int is_refund = -1;

    private void getData() {
        if (is_refund == -1)
            new HttpRequest<DefaultResponse>()
                    .with(this).setApiCode(ApiCst.isRefundCommon)
                    .addParam("token", App.getToken(mContext))
                    .addParam("order_id", orderId)
                    .setListener(new HttpRequest.OnNetworkListener<DefaultResponse>() {
                        @Override
                        public void onSuccess(DefaultResponse response) {
                            try {
                                JSONObject object = new JSONObject(response.content);
                                is_refund = object.optInt("is_refund", 0);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            setView();
                        }

                        @Override
                        public void onFail(String message, DefaultResponse response) {
                            toast(message);
                            finish();
                        }
                    }).start(new DefaultResponse());


        new HttpRequest<GoodsOrderInfoResponse>()
                .with(this).setApiCode(isVisitor ? ApiCst.getOrderAgentdetail : ApiCst.getOrderDetail)
                .addParam("token", App.getToken(mContext))
                .addParam("order_id", orderId)
                .setListener(new HttpRequest.OnNetworkListener<GoodsOrderInfoResponse>() {
                    @Override
                    public void onSuccess(GoodsOrderInfoResponse response) {
                        model = response.model;
                        setView();
                    }

                    @Override
                    public void onFail(String message, GoodsOrderInfoResponse response) {
                        toast(message);
                        finish();
                    }
                }).start(new GoodsOrderInfoResponse());


    }

    @Override
    protected void initListener() {
        getRightText().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (model == null) return;
                if (isVisitor) return;
                if (model.getStatus() == 0) {
                    //取消订单
                    new CommonDialog.Builder(GoodsOrderActivity.this)
                            .setCancelable(false)
                            .setMessage("确定取消该订单吗？")
                            .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                }
                            })
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                    confirmOrCancel(60);
                                }
                            }).show();
                } else if (model.getStatus() == 10) {
                    GoodsOrderEdtAddressActivity.startActivity(mContext, model);
                } else if (model.getStatus() == 20 || model.getStatus() == 30 || model.getStatus() == 40) {
                    String content = "订单号：" + model.getOrder_no() + "\n" +
                            "物流公司：" + model.getExpress_name() + "\n" +
                            "物流单号：" + model.getExpress_no();
                    CommonUtils.clipData(mContext, content);
                    toast("物流信息复制成功");
                }
            }
        });

    }


    private void enter() {
        switch (model.getStatus()) {
            // 0-待付款
            case 0:
                PayActivity.startActivity(this, String.valueOf(model.getOrder_id()), model.getPay_price());
                break;
            // 20-待收货
            case 20:
                confirm();
                break;
            default:
                break;
        }

    }

    /**
     * 确认收货
     */
    private void confirm() {
        ConfirmGoodsDialog confirmGoodsDialog = new ConfirmGoodsDialog(this);
        confirmGoodsDialog.setListener(new DialogEnterListener() {
            @Override
            public void cancel(Object tag) {

            }

            @Override
            public void enter(Object tag) {
                confirmOrCancel(30);
            }
        });
        confirmGoodsDialog.show();
    }

    /**
     * 确认收货或取消订单
     * 30-确认收货 60-取消订单
     *
     * @param status
     */
    public void confirmOrCancel(int status) {
        new HttpRequest<DefaultResponse>()
                .with(this).setApiCode(ApiCst.confirmOrCancel)
                .addParam("token", App.getToken(mContext))
                .addParam("order_id", orderId)
                .addParam("status", status)
                .setListener(new HttpRequest.OnNetworkListener<DefaultResponse>() {
                    @Override
                    public void onSuccess(DefaultResponse response) {
                        toast(response.message);
                        getData();
                    }

                    @Override
                    public void onFail(String message, DefaultResponse response) {
                        toast(message);
                    }
                }).start(new DefaultResponse());

    }


    @OnClick({R.id.tv_express_find, R.id.ll_server, R.id.ll_order_code_copy, R.id.ll_enter})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_express_find:
                if (isVisitor) return;
                CourierInfoActivity.startActivity(this, orderId, false, -1);
                break;
            case R.id.ll_server:
                new KefuDialog(this).show(1);
                break;
            case R.id.ll_order_code_copy:
                findViewById(R.id.ll_order_code_copy).setEnabled(false);
                CommonUtils.clipData(this, model.getOrder_no());
                toast("复制成功");
                findViewById(R.id.ll_order_code_copy).setEnabled(true);
                break;
            case R.id.ll_enter:
                if (isVisitor) return;
                llEnter.setEnabled(false);
                enter();
                llEnter.setEnabled(true);
                break;

        }
    }


    @Override
    public void onClick(View v) {
        super.onClick(v);
        if (v.getTag() != null && v.getTag() instanceof GoodsItemModel) {
            final GoodsItemModel model = (GoodsItemModel) v.getTag();
            if (v.getId() == R.id.tv_refund) {
                if (isVisitor) return;
                if (model.getOrder_goods_status() == 0) {
                    new CommonDialog.Builder(GoodsOrderActivity.this)
                            .setCancelable(false)
                            .setMessage("申请退换货，请先联系售后客服，未经沟通直接申请，一律不予处理！")
                            .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                }
                            })
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                    ApplyRefundActivity.startActivity(GoodsOrderActivity.this, orderId, model);
                                }
                            }).show();
                } else {
                    RefundInfoActivity.startActivity(this, orderId, model);
                }
                return;
            }
            GoodsActivity.startActivity(this, model.getGoods_id());
        }
    }

    @Override
    protected void onResume() {
        getData();
        super.onResume();
    }

    @Override
    public void onBackPressed() {
        if (backMain) {
            Intent intent = new Intent(this, MainActivity.class);
            intent.putExtra("intentToIndexFragment", true);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
            finish();
        } else
            super.onBackPressed();
    }


}
